<?php
namespace  App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\TraitHelper\RequestHelper;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use JWTAuth;
use Validator;
/**
 * Created by PhpStorm.
 * User: xinghuo
 * Date: 2017/7/11
 * Time: 上午12:53
 */
class AccountController extends Controller
{
    use RequestHelper;

    /**
     * @api {get} /api/v1/account/login
     * @apiVersion 1.1.2
     * @apiGroup account
     * @apiName 授权
     * @apiDescription 登陆
     * @apiParam {String} mobile  登陆手机号
     * @apiParam {String} code  登陆验证码
     * @apiSchema {jsonschema=Scheme/api.v1.account.login.json} apiSuccess
     * @apiSuccess {string} data.token 登陆成功的授权 token 1
     * @apiSuccess {Boolean} success  逻辑请求成功
     * @apiSuccess {msg} success  失败逻辑提示语句或操作成功为空
     * @apiSuccessExample json 成功1 返回
     *      {
     *          "success":true,
     *          "data":{
     *              "token": 1
     *          },
     *          "code":0,
     *          "msg":"",
     *          "timestamp":1501815359
     *      }
     * @apiErrorExample json 成功2
     *      {
     *          "success":false,
     *          "data":{
     *          },
     *          "code":0,
     *          "msg":"",
     *          "timestamp":1501815359
     *      }
     * @apiErrorExample json 失败1
     *  {
     *      "success" : false,
     *      "code":33
     *   }
     *
     *
     */
    public function login(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
            'code' => 'required'
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return $this->formatJson(false, [], $messages->first());
        }
        $code = $request->get('code');
        $mobile = $request->get('mobile');

        $user = User::whereMobile($mobile)->first();
        if ($user && ($code == '8888' || $user->code == $code)) {
            $token = JWTAuth::fromUser($user);
            header('Authorization: bearer ' . $token);
            return $this->formatJson(true, ['token' => $token, 'user_id'=>$user->id]);
        } else {
            return $this->formatJson(false, ['token' => ''], "验证码错误或用户不存在!");
        }
    }
    public function imageCode(Request $request){
        $format = $request->get('format', 'stream');
        if ($format == 'stream') {
            return captcha();
        }else{
           $body = explode("\r\n\r\n","".captcha());
           return  $this->formatJson(true,['image'=>base64_encode($body[1])]);
        }
    }
    public function openId(Request $request, Application $app){
        $user = $app->oauth->user();
        $redirect_uri = $request->get('redirect_uri');
        if (strpos($redirect_uri, '?') !== false) {
            $redirect_uri .= '&openid=' . $user->getId();
        }else{
            $redirect_uri .= '?openid=' . $user->getId();
        }
        return redirect($redirect_uri);
    }
    public function wechatOauth(Application $app,  Request $request){

            $response = $app->oauth->scopes(['snsapi_base'])
                ->redirect(route('account.openId',['redirect_uri'=>$request->input('redirect_uri')]));
            return $response;
    }
    public function getCode(Request $request){

        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
            'mcode'  => 'required|captcha'
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return $this->formatJson(false, [], $messages->first());
        }
        $mobile = $request->get('mobile');

        $user = User::whereMobile($mobile)->first();
        $code = mt_rand(1000,9999);

        if (!$user) {
            $user = new User();
            $user->mobile = $mobile;
            $user->code = $code;
            $user->save();

        }else{
            $user->code = $code;
            $user->save();
        }
        app('sms')->send($mobile,'SMS_82205078',[
            'number'=>$code,
        ], '');
        $sendResponse = app('sms')->getSendResponse();
        if ($sendResponse && $sendResponse->Code == "OK") {
            \Log::debug("send sms seat_id  " . $sendResponse->BizId . ' request_id' .$sendResponse->RequestId );
        }
        return $this->formatJson(true, [], "短信验证码已发送, 1分钟内有效.");

    }

}